﻿using System;
using System.Collections.ObjectModel;
using System.Xml;

namespace Graphe.Collations
{
    public class FragmentCollection : ICollationCollection<Fragment>, ICollationElement, IComparable<FragmentCollection>
    {
        #region ICollationElement Members

        public void Parse(XmlReader reader, CollationDebugMessages debugMessages)
        {
            using(XmlReader subReader = reader.ReadSubtree())
            {
                while (subReader.ReadToFollowing("Fragment"))
                {
                    Fragment fragment = new Fragment();
                    fragment.Parse(subReader, debugMessages);
                    Add(fragment);
                }

                reader.Read();
            }
        }

        public void Render(XmlTextWriter writer)
        {
            writer.WriteStartElement("Fragments");

            foreach (Fragment fragment in this)
                fragment.Render(writer);

            writer.WriteEndElement();
        }

        #endregion
        #region IComparable<FragmentCollection> Members

        public int CompareTo(FragmentCollection other)
        {
            if (Count != other.Count)
                return -1;

            foreach (Fragment fragment in this)
            {
                bool foundMatch = false;
                foreach (Fragment fragment2 in other)
                {
                    if (fragment.CompareTo(fragment2) == 0)
                    {
                        foundMatch = true;
                        break;
                    }
                }

                if (!foundMatch)
                    return -1;
            }

            foreach (Fragment fragment in other)
            {
                bool foundMatch = false;
                foreach (Fragment fragment2 in this)
                {
                    if (fragment.CompareTo(fragment2) == 0)
                    {
                        foundMatch = true;
                        break;
                    }
                }

                if (!foundMatch)
                    return -1;
            }

            return 0;
        }

        #endregion
    }
}
